﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Specialized;
using AlipayClass;
using Service;
using Data.Entity;

namespace ECommerce.Alipay
{
	public partial class Return : BasePage
	{
		private IOrderService _OrderService;
		private ICashTicketService _CashTicketService;

		protected void Page_Load(object sender, EventArgs e)
		{
			SortedDictionary<string, string> sArrary = GetRequest();
			///////////////////////以下参数是需要设置的相关配置参数，设置后不会更改的//////////////////////
			string partner = "2088302091633148";                //合作身份者ID
			string key = "rs8e8p90hciw3rlwqtvxjhqfu3s0f6kz";    //安全检验码
			string input_charset = "utf-8";                     //字符编码格式 目前支持 gbk 或 utf-8
			string sign_type = "MD5";                           //加密方式 不需修改
			string transport = "http";                         //访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
			//////////////////////////////////////////////////////////////////////////////////////////////

			if (sArrary.Count > 0)//判断是否有带返回参数
			{
				AlipayNotify aliNotify = new AlipayNotify(sArrary, Request.QueryString["notify_id"], partner, key, input_charset, sign_type, transport);
				string responseTxt = aliNotify.ResponseTxt; //获取远程服务器ATN结果，验证是否是支付宝服务器发来的请求
				string sign = Request.QueryString["sign"];  //获取支付宝反馈回来的sign结果
				string mysign = aliNotify.Mysign;           //获取通知返回后计算后（验证）的加密结果

				//写日志记录（若要调试，请取消下面两行注释）
				//string sWord = "responseTxt=" + responseTxt + "\n return_url_log:sign=" + Request.QueryString["sign"] + "&mysign=" + mysign + "\n return回来的参数：" + aliNotify.PreSignStr;
				//AlipayFunction.log_result(Server.MapPath("log/" + DateTime.Now.ToString().Replace(":", "")) + ".txt",sWord);

				//判断responsetTxt是否为ture，生成的签名结果mysign与获得的签名结果sign是否一致
				//responsetTxt的结果不是true，与服务器设置问题、合作身份者ID、notify_id一分钟失效有关
				//mysign与sign不等，与安全校验码、请求时的参数格式（如：带自定义参数等）、编码格式有关
				if (responseTxt == "true" && sign == mysign)//验证成功
				{
					//获取支付宝的通知返回参数
					string trade_no = Request.QueryString["trade_no"];              //支付宝交易号
					string order_no = Request.QueryString["out_trade_no"];	        //获取订单号
					string total_fee = Request.QueryString["price"];	            //获取总金额
					string subject = Request.QueryString["subject"];                //商品名称、订单名称
					string body = Request.QueryString["body"];                      //商品描述、订单备注、描述
					string buyer_email = Request.QueryString["buyer_email"];        //买家支付宝账号
					string receive_name = Request.QueryString["receive_name"];      //收货人姓名
					string receive_address = Request.QueryString["receive_address"];//收货人地址
					string receive_zip = Request.QueryString["receive_zip"];        //收货人邮编
					string receive_phone = Request.QueryString["receive_phone"];    //收货人电话
					string receive_mobile = Request.QueryString["receive_mobile"];  //收货人手机
					string trade_status = Request.QueryString["trade_status"];      //交易状态
					//int sOld_trade_status = 0;							            //获取商户网站数据库中查询得到该笔交易当前的交易状态（商户自行编写）

					//打印页面
					lbTrade_no.Text = trade_no;
					lbOut_trade_no.Text = order_no;
					lbTotal_fee.Text = total_fee;
					//lbSubject.Text = subject;
					//lbBody.Text = body;
					//lbBuyer_email.Text = buyer_email;
					//LbName.Text = receive_name;
					//LbAddress.Text = receive_address;
					//LbZip.Text = receive_zip;
					//LbPhone.Text = receive_phone;
					//LbMobile.Text = receive_mobile;
					lbTrade_status.Text = trade_status;
					lbVerify.Text = "验证成功";

					var theOrder = GetTheOrder(order_no);
					//sOld_trade_status = theOrder.OrderStatusID.Value;
					var theOrderStatus = _OrderService.GetAllOrderStatus().Where(exp => exp.OrderStatusID == theOrder.OrderStatusID).FirstOrDefault();

					//假设：
					//sOld_trade_status=0	表示订单未处理；
					//sOld_trade_status=1	表示买家已在支付宝交易管理中产生了交易记录，但没有付款
					//sOld_trade_status=2	表示买家已在支付宝交易管理中产生了交易记录且付款成功，但卖家没有发货
					//sOld_trade_status=3	表示卖家已经发了货，但买家还没有做确认收货的操作
					//sOld_trade_status=4	表示买家已经确认收货，这笔交易完成

					if (Request.QueryString["trade_status"] == "WAIT_SELLER_SEND_GOODS")
					{
						//为了保证不被重复调用，或重复执行数据库更新程序，请判断该笔交易状态是否是订单未处理状态
						if (theOrderStatus.OrderStatusNumber != (int)Data.Entity.OrderStatuses.WAIT_SELLER_SEND_GOODS)
						{
							//根据订单号更新订单，把订单状态处理成交易成功

							if (theOrder != null)
							{
								if (_OrderService == null)
								{
									_OrderService = new OrderService();
								}

								var theNewOrderStatus = _OrderService.GetTheOrderStatusByStatusName("WAIT_SELLER_SEND_GOODS");

								theOrder.OrderStatusID = theNewOrderStatus.OrderStatusID;
								theOrder.PurchaseOrderNumber = trade_no;
								theOrder.PaymentStatusID = (int)Data.Entity.PaymentStatuses.Payed;

								UpdateTheOrder(theOrder);

								if(theOrder.CashTicketId.HasValue && theOrder.CashTicketId > 0 && theOrder.OrderDiscount > 0)
								{
									// update the cashticket if exist
									if (_CashTicketService == null)
									{
										_CashTicketService = new Service.CashTicketService();
									}

									_CashTicketService = new Service.CashTicketService();

									Data.Entity.CashTicket theCashTicket = _CashTicketService.GetMyCashTicket(theOrder.UserID).Where(exp => exp.CashTicketID == theOrder.CashTicketId).FirstOrDefault();
									
									if(theCashTicket != null)
									{
										if(theOrder.OrderDiscount < theCashTicket.Cost)
										{
											theCashTicket.Cost -= theOrder.OrderDiscount.Value;
											_CashTicketService.UpdateCashTicket(theCashTicket);
										}
										else
										{
											theCashTicket.IsUsed = 1;
											_CashTicketService.UpdateCashTicket(theCashTicket);
										}
									}
								}

								//add note 
								var theOrderNote = new Data.Entity.OrderNote();

								theOrderNote.CreatedOn = DateTime.Now;
								theOrderNote.DisplayToUser = true;
								theOrderNote.Note = GetLocalResourceString(theNewOrderStatus.Name);
								theOrderNote.OrderID = theOrder.OrderID;

								if (_OrderService == null)
								{
									_OrderService = new OrderService();
								}

								_OrderService.CreateNewOrderNote(theOrderNote);
							}
						}
					}
					else
					{
						lbTrade_status.Text = Request.QueryString["trade_status"];

						//add note 
						var theOrderNote = new Data.Entity.OrderNote();

						theOrderNote.CreatedOn = DateTime.Now;
						theOrderNote.DisplayToUser = true;
						theOrderNote.Note = Request.QueryString["trade_status"];
						theOrderNote.OrderID = theOrder.OrderID;

						if (_OrderService == null)
						{
							_OrderService = new OrderService();
						}

						_OrderService.CreateNewOrderNote(theOrderNote);
					}
				}
				else//验证失败
				{
					lbVerify.Text = "验证失败" + "/responseTxt:" + responseTxt  + "/sign:"+ sign;
				}
			}
			else
			{
				lbVerify.Text = "无返回参数";
			}
		}

		/// <summary>
		/// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
		/// </summary>
		/// <returns>request回来的信息组成的数组</returns>
		public SortedDictionary<string, string> GetRequest()
		{
			int i = 0;
			SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
			NameValueCollection coll;
			//Load Form variables into NameValueCollection variable.
			coll = Request.QueryString;

			// Get names of all forms into a string array.
			String[] requestItem = coll.AllKeys;

			for (i = 0; i < requestItem.Length; i++)
			{
				sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
			}

			return sArray;
		}

		private Order GetTheOrder(string orderNumber)
		{
			if (string.IsNullOrEmpty(orderNumber))
			{
				return null;
			}

			if (_OrderService == null)
			{
				_OrderService = new OrderService();
			}

			return _OrderService.GetTheOrderByOrderNumber(orderNumber);
		}

		private int UpdateTheOrder(Order theOrder)
		{
			if (theOrder == null || theOrder.OrderID <= 0)
			{
				return 0;
			}

			if (_OrderService == null)
			{
				_OrderService = new OrderService();
			}

			return _OrderService.UpdateOrder(theOrder);
		}
	}
}
